"""
@Project:ruiji
@File:index.py
@Author:马可
@Date:上午 09:38
"""
from email.mime import image
from itertools import count
import re
from flask import Blueprint,jsonify,request,redirect
from db import db
from procom import get_ali_object
from utils.myredis import r
import json
import datetime
import random

index_blue = Blueprint('index',__name__)


# 获取商家信息
@index_blue.route("/getshops")
def getshops():
    #读取缓存，如果有直接返回，没有查询数据库
    code = '001'
    key = "shop"+code
    #获取缓存中数据
    shop = r.get_str(key)
    if not shop:
        #并发访问的时候，只能一个人访问
        res = r.setnx_str(key+'exit',key+'exit')
        if res:
            sql = "select * from shops where code='001'"
            shop = db.find(sql)
            r.set_str(key,json.dumps(shop))
    else:
        shop = json.loads(shop)
    return jsonify({"code":200,'shops':shop})


# 获取所有分类
@index_blue.route("/getcates")
def getcates():
    r.remove_str("cates")
    cates = r.get_str('cates')
    if not cates:
        sql="select id,name,type from category order by sort asc"
        res = db.find_all(sql)
        data = [{'id':str(i['id']),'text':i['name'],'type':i['type']} for i in res]
        r.set_str('cates',json.dumps(data))
    else:
        data = json.loads(cates)
    return jsonify({"code":200,'catelist':data})



#根据分类id获取此分类下的所有商品
@index_blue.route("/getGoodsBycateid")
def getGoodsBycateid():
    #获取分类id
    cateid = request.args.get('cateid')
    r.remove_str('goods'+cateid)
    #获取缓存中此分类下的商品
    goods = r.get_str('goods'+cateid)
     
    #如果不存在查询
    if not goods:
        sql="select id,name,price,image,description from dish where category_id=%d and is_deleted=0"%(int(cateid))
        res = db.find_all(sql)
        #根据菜品id查询对应的口味信息
        data=[]
        for i in res:
            dict={'id':str(i['id']),'name':i['name'],'price':float(i['price']),'image':i['image'],'description':i['description']}
            sql1 = "select value from dish_flavor where dish_id=%d"%(int(i['id']))
            flavors=db.find_all(sql1)
            flist=[]
            for j in flavors:
                flist.append(json.loads(j['value']))
            dict['flavors'] = flist
            data.append(dict)
        #把decimal转成float
        # data = [{'id':str(i['id']),'name':i['name'],'price':float(i['price']),'image':i['image'],'description':i['description']} for i in res] 
        #加入缓存
        r.set_str('goods'+cateid,json.dumps(data))
    else:
        data = json.loads(goods)
    return jsonify({"code":200,'goodslist':data})



# 购物车添加
@index_blue.route('/addcate')
def addcart():
    #获取参数 userid  gid  count  ["少糖","少盐"] type(1菜品  2套餐)
    userid = request.args.get('userid')
    gid = request.args.get('gid')
    count = request.args.get('count')
    type = request.args.get('type')
    flavors = request.args.get('flavors')
    if not all([userid,gid,count,type,flavors]):
        return jsonify({"code":10010,'mes':'参数错误'})
    #查询购物车中某个商品是否存在
    pkey = 'cart'+str(userid)+'goods'+str(gid)
    flag = r.is_exits(pkey)
   
    if int(flag) == 0:
        #不存在添加
        r.hash_add(pkey,gid,count)
        r.hash_add(pkey,'type',type)
        r.hash_add(pkey,'flavors',flavors)
        #把商品名称和价格以name和price存入
    else:
        #存在数量更新
        r.hash_hincrby(pkey,gid,count,1)
    #返回结果
    return jsonify({"code":200,'mes':'购买成功'})

# 我的购物车数据封装
def getcartdata(userid):
     #根据userid模糊查询购物车信息
    carts = r.findall_str('cart'+str(userid))
    #遍历购物车，查每一个商品的属性
    clist=[]
    tcount=0
    for i in carts:
        dict={}
        goods = r.hash_getall(i.decode())
        for k,v in goods.items():
            kk = k.decode()
            vv = v.decode()
            # print("kk="+str(kk)+"vv="+str(vv))
            if kk == "type":
                dict['type']=vv
            elif kk == 'flavors':
                dict['flavors'] = json.loads(vv)
            else:
                dict['id']=kk
                dict['count']=vv    
                tcount +=int(vv)
        clist.append(dict)
    tmoney=0
   
    if len(clist)>0:
        for i in clist:
            #根据id和类型查询名称和价格 1单品2套餐
            if int(i['type']) == 1:
                sql = "select name,price,image from dish where id=%d"%(int(i['id']))
            else:
                sql = "select name,price,image from setmeal where id=%d"%(int(i['id']))
            res = db.find(sql)
            i['name'] = res['name']
            i['image'] = res['image']
            i['price'] = float(res['price']) 
            tmoney+= i['price']*int(i['count'])
    return clist,tmoney,tcount


#我的购物车
@index_blue.route('/addcart')
def mycart():
    #获取userid
    userid = request.args.get('userid')
    clist,tmoney,tcount=getcartdata(userid)
    return jsonify({"code":200,'clist':clist,'tmoney':tmoney,'tcount':tcount})


def xtree(data):
    list1 = []
    # 判断data长度
    if len(data)<=0:
        return list1
    # 把data处理成字点
    dict = {}
    for i in data:
        dict[i['code']] = i

    for j in data:
        # 判断是否为一级
        pid = j['pid']
        if pid ==None:
            list1.append(j)
        else:
            # 判断这个id对应的父级有没有son
            if 'son' not in dict[pid]:
                dict[pid]['son']=[]
            dict[pid]['son'].append(j)
    return list1 


# 无限级分类、省市区
@index_blue.route('/index_blue')
def index_blues():
    # redis
    citylist = r.get_str("citylist")
    if not citylist:
        sql = "select * from tb_areas"
        res = db.find_all(sql)
        list = xtree(res)
        r.set_str('citylist',json.dumps(list))
    else:
        list = json.loads(citylist)
    return jsonify({
        "code":200,
        "list":list,
    })


@index_blue.route('/jiajian')
def jiajian():
    #获取参数 userid gid count type
    userid = request.args.get('userid')
    gid = request.args.get('gid')
    count = request.args.get('count')
    type = request.args.get('type')
    #查询购物车中此商品是否存在
    key = "cart"+str(userid)+'goods'+str(gid)
    if r.is_exits(key):
        tcount = count
        #1加 2减
        if type == 2:
            tcount = "-"+str(count)
        res = r.hash_hincrby(key,gid,tcount,type)
        #判断结果
        if res == False:
            return jsonify({"code":10011,'mes':'减的数量必须小于当前购买数量'})
        else:
            return jsonify({"code":200})
    else:
        return jsonify({"code":10010,'mes':'没买过此商品'})




# 添加订单
@index_blue.route('/add_orders')
def add_orders():
    #获取用户输入
    # "userid":300,
    #         'address_id':this.chosenAddressId,'message':this.message,'paytype':this.paytype
    data = json.loads(request.data)
    userid = data['userid']
    address_id = data['address_id']
    message = data['message']
    paytype=data['paytype']
    #根据购物车查价格图片
    #redis hash获取我的购物车
    clist,tmoney,tcount=getcartdata(userid)
    #事务处理s
    #写入订单表
    #订单号  年月日时分秒+userid+5位随机数
    now = datetime.datetime.strftime(datetime.datetime.now(),'%Y-%m-%d %H%M%S')
    code = datetime.datetime.strftime(datetime.datetime.now(),'%Y%m%d %H%M%S')+str(userid)+str(random.randint(10000,99999))
    #写入订单表
    sql = "insert into orders(number,status,user_id,"
    +"address_book_id,order_time,pay_method,amount,remark,phone,address,user_name,consignee) "
    +"values('%s',%d,%d,%d,'%s',%d,'%s','%s','%s','%s','%s','%s')"%(code,1,int(userid),int(address_id),now,int(paytype),tmoney,message,'1','1','1','1')
    print(sql)
    db.update(sql)
    #写入详情表
    for i in clist:
        sql1 = "insert into detail"
        db.update(sql1)
    db.commit()

    #清空购物车
    r.removeall_str('cart'+str(userid))
    return jsonify({
        'code':200,
    })
    
    return 'ok'


# 支付宝
@index_blue.route('/getpayurl')
def getpayur():
    order_code = request.args.get("order_code")
    # 查询数据库
    sql = "select amount from orders where number='%s'"%(order_code)
    res = db.find(sql)
    print('aaa',res)
    if res:
        # 存入set
        r.set_add('payorderlist',order_code)
        alipay = get_ali_object()
        # 生成支付的url
        query_params = alipay.direct_pay(
            subject="test", # 商品描述
            out_trade_no=str(order_code),  # 商品订单号
            total_amount=float(res['amount']),    # 交易金额
        )
        pay_url = "http://openapi.alipaydev.com/gateway.do?{0}".format(query_params)
        return jsonify({
            'code':200,
            'url':pay_url,
        })
    else:
        return jsonify({
            'code':30010,
            'msg':'没有此订单',
        })


@index_blue.route('/callback')
def callback():
    trade_no = request.args.get('trade_no') # 流水号
    out_trade_no = request.args.get('out_trade_no') # 订单号
    # 从set上清除
    r.set_delvalue('payorderlist',out_trade_no)
    # 更新订单表
    now = datetime.datetime.strftime(datetime.datetime.now(),'%Y-%m-%d %H:%M:%s')
    sql = "update orders set status=2,trade_on='%s',checkout_time='%s' where number='%s'"%(trade_no,now,out_trade_no)
    db.update(sql)
    # 更新销量
    # 订单详情表
    sql = "select dish_id,setmeal_id,number from order_detail where order_id='%s'"%(out_trade_no)
    res = db.find_all(sql)
    for i in res:
        if res['dish_id']>0:
            # 更新菜品
            gsql = "update dish set sales=sales+%d where id=%d"%(int(i['number']),int(i['dish_id']))
        else:
            # 更新套餐
            gsql = "update setmeal set seles=sales+%d where id=%d"%(int(i['number']),int(i['setmeal_id']))
        db.update(gsql)